package org.jsola.hr.web;

import org.jsola.approval.vo.UserApproVO;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.TransferAccountsBatchAddDTO;
import org.jsola.hr.dto.TransferAccountsBatchAgainAddDTO;
import org.jsola.hr.dto.TransferAccountsBatchUpdateDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.*;
import org.jsola.hr.service.ITransferAccountsBatchService;
import org.jsola.hr.vo.*;
import org.jsola.hr.vo.payAli.AliPayUrlVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;


/**
 * 转账批次
 *
 * @author zhr
 */
@RestController("hrTransferAccountsBatchController")
@RequestMapping(HrConstants.API_PATH + "/v1/transferAccountsBatches")
public class TransferAccountsBatchController implements ITransferAccountsBatchControllerAPI {

    @Autowired
    private ITransferAccountsBatchService transferAccountsBatchService;

    @Value("${onekeypay.ali.authorizationUrl}")
    private String authorizationUrl;

    @Override
    @PostMapping
    public Result<TransferAccountsBatchVO> save(@Valid @RequestBody TransferAccountsBatchAddDTO transferAccountsBatchAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增转账批次权限校验

        return Result.success(
                transferAccountsBatchService.saveLogic(transferAccountsBatchAddDTO, tokenUser)
        );
    }

    @Override
    @PostMapping("/saveBatchAndDetail")
    public Result<TransferAccountsDetailImportAllVO> saveBatchAndDetail(@Valid @RequestBody TransferBuildDetailQuery transferBuildDetailQuerye) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增转账批次权限校验

        return Result.success(
                transferAccountsBatchService.saveBatchAndDetail(transferBuildDetailQuerye, tokenUser)
        );
    }

    @Override
    @PostMapping("/saveAgainByBatchId")
    public Result<TransferAccountsBatchVO> saveAgainByBatchId(@Valid @RequestBody TransferAccountsBatchAgainAddDTO transferAccountsBatchAgainAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增转账批次权限校验

        return Result.success(
                transferAccountsBatchService.saveAgainByBatchId(transferAccountsBatchAgainAddDTO, tokenUser)
        );
    }

    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody TransferAccountsBatchUpdateDTO transferAccountsBatchUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改转账批次权限校验

        int count = transferAccountsBatchService.update(transferAccountsBatchUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }



    @Override
    @DeleteMapping(value = "/{transferAccountsBatchId}")
    public Result<Integer> delete(@PathVariable String transferAccountsBatchId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除转账批次权限校验

        int count = transferAccountsBatchService.deleteByIds(tokenUser, transferAccountsBatchId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] transferAccountsBatchIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除转账批次权限校验

        int count = transferAccountsBatchService.deleteByIds(tokenUser, transferAccountsBatchIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{transferAccountsBatchId}")
    public Result<TransferAccountsBatchVO> findById(@PathVariable String transferAccountsBatchId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看转账批次权限校验

        return Result.success(
            transferAccountsBatchService.selectById(transferAccountsBatchId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<TransferAccountsBatchListVO>> listAll(@Valid TransferAccountsBatchQuery transferAccountsBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看转账批次权限校验

        return Result.success(
            transferAccountsBatchService.select(transferAccountsBatchQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<TransferAccountsBatchListVO>> page(@Valid TransferAccountsBatchQuery transferAccountsBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
            transferAccountsBatchService.selectPage(transferAccountsBatchQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping("/pagePost")
    public Result<Page<TransferAccountsBatchListVO>> pagePost(@RequestBody TransferAccountsBatchQuery transferAccountsBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                transferAccountsBatchService.selectPage(transferAccountsBatchQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping(value = "startApprover/{transferAccountsBatchId}/{flowId}")
    public Result<UserApproVO> startApprover(@PathVariable String transferAccountsBatchId, @PathVariable String flowId) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                transferAccountsBatchService.startApprover(transferAccountsBatchId, flowId, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/pageApproving")
    public Result<Page<TransferAccountsBatchListVO>> pageApproving(TransferAccountsBatchQuery transferAccountsBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看转账批次权限校验

        return Result.success(
                transferAccountsBatchService.pageApproving(transferAccountsBatchQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/pageApprovedPass")
    public Result<Page<TransferAccountsBatchListVO>> pageApprovedPass(TransferAccountsBatchQuery transferAccountsBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看转账批次权限校验

        return Result.success(
                transferAccountsBatchService.pageApprovedPass(transferAccountsBatchQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/pageApprovedReject")
    public Result<Page<TransferAccountsBatchListVO>> pageApprovedReject(TransferAccountsBatchQuery transferAccountsBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看转账批次权限校验

        return Result.success(
                transferAccountsBatchService.pageApprovedReject(transferAccountsBatchQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/pageApproveNotifierMe")
    public Result<Page<TransferAccountsBatchListVO>> pageApproveNotifierMe(TransferAccountsBatchQuery transferAccountsBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看转账批次权限校验

        return Result.success(
                transferAccountsBatchService.pageApproveNotifierMe(transferAccountsBatchQuery, tokenUser)
        );
    }

    @Override
    @PostMapping("/pageApprove")
    public Result<Page<TransferAccountsBatchListVO>> pageApprove(@RequestBody @Valid TransferAccountsBatchQuery transferAccountsBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看转账批次权限校验

        return Result.success(
                transferAccountsBatchService.pageApprove(transferAccountsBatchQuery, tokenUser)
        );
    }


    @Override
    @PostMapping("/saveBatchAndDetailByFile")
    public Result<TransferAccountsDetailImportAllVO> saveBatchAndDetailByFile(@RequestParam("file")  MultipartFile file,
                                                                              @RequestParam("companyId") String companyId,
                                                                              @RequestParam("companyName") String companyName,
                                                                              @RequestParam("type") Integer type,
                                                                              @RequestParam("orderTitle") String orderTitle,
                                                                              @RequestParam(name = "remark", required = false) String remark) {
        TokenUser tokenUser = UserContext.getUser();

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                transferAccountsBatchService.saveBatchAndDetailByFile(excelFile, companyId, companyName,
                        type, orderTitle, remark, tokenUser)
        );
    }

    @Override
    @PostMapping("/zfbStartTransferAccounts")
    public Result<AliPayUrlVO> zfbStartTransferAccounts(@Valid @RequestBody TransferStartZfbBatchQuery transferStartZfbBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                transferAccountsBatchService.zfbStartTransferAccounts(transferStartZfbBatchQuery, tokenUser)
        );
    }

    @Override
    @GetMapping("/sendSafetyPayPhoneMessage/{phone}")
    public Result<Boolean> sendSafetyPayPhoneMessage(@PathVariable  String phone) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                transferAccountsBatchService.sendSafetyPayPhoneMessage(phone, tokenUser)
        );
    }

    @Override
    @PostMapping("/zfbSafetyStartTransferAccounts")
    public Result<String> zfbSafetyStartTransferAccounts(@Valid @RequestBody TransferStartZfbSafetyBatchQuery transferStartZfbSafetyBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                transferAccountsBatchService.zfbSafetyBatchStartTransferAccounts(transferStartZfbSafetyBatchQuery, tokenUser)
        );
    }

    @Override
    @PostMapping("/zfbSafetyStartTransferAccountsToBankCard")
    public Result<String> zfbSafetyStartTransferAccountsToBankCard(@Valid @RequestBody TransferStartZfbSafetyBatchQuery transferStartZfbSafetyBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                transferAccountsBatchService.zfbSafetyStartTransferAccountsToBankCard(transferStartZfbSafetyBatchQuery, tokenUser)
        );
    }

    @Override
    @PostMapping("/vxStartTransferAccounts")
    public Result<Integer> vxStartTransferAccounts(@Valid @RequestBody TransferStartVxBatchQuery transferStartVxBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();
        transferAccountsBatchService.vxStartTransferAccounts(transferStartVxBatchQuery, tokenUser);
        return Result.success(1);
    }

    @Override
    @PostMapping("/pingAnStartTransferAccounts")
    public Result<Integer> pingAnStartTransferAccounts(@Valid @RequestBody TransferStartPingAnBankBatchQuery transferStartPingAnBankBatchQuery) {
        TokenUser tokenUser = UserContext.getUser();
        transferAccountsBatchService.pingAnStartTransferAccounts(transferStartPingAnBankBatchQuery, tokenUser);
        return Result.success(1);
    }

    @Override
    @GetMapping("/selectTransferAccountsBatch/{salaryTransferAccountsBatchId}")
    public Result<Integer> selectTransferAccountsBatch(@PathVariable String salaryTransferAccountsBatchId) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                transferAccountsBatchService.selectTransferAccountsBatch(salaryTransferAccountsBatchId, tokenUser)
        );
    }

    @Override
    @GetMapping("/setAppAuthTokenToRedis/{appAuthCode}")
    public Result<Integer> setAppAuthTokenToRedis(@PathVariable String appAuthCode) {
        TokenUser tokenUser = UserContext.getUser();

        transferAccountsBatchService.setAppAuthTokenToRedis(appAuthCode);
        return Result.success(1);
    }

    @Override
    @GetMapping("/statisticsBatchStatusBySite")
    public Result<TransferAccountsBatchStatisticsVO> statisticsBatchStatusBySite() {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                transferAccountsBatchService.statisticsBatchStatusByCompanyIds(null, tokenUser)
        );
    }

    @Override
    @PostMapping("/statisticsBatchStatusByCompanyIds")
    public Result<TransferAccountsBatchStatisticsVO> statisticsBatchStatusByCompanyIds(@RequestBody List<String> companyIds) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                transferAccountsBatchService.statisticsBatchStatusByCompanyIds(companyIds, tokenUser)
        );
    }


    @Override
    @GetMapping("/returnAuthorizationUrl")
    public Result<String> returnAuthorizationUrl() {
        String url;
        try {
            url = "https://openauth.alipay.com/oauth2/appToAppAuth.htm?" +
                    "app_id=2021002187615001&" +
                    "redirect_uri=" + URLEncoder.encode(authorizationUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new ParamException("拉取授权页面失败，请联系管理员！");
        }
        return Result.success(url);
    }

    @Override
    @GetMapping("/buildAllInfo")
    public Result<List<TransferBuildDetailAddVO>> buildAllInfo(Integer type, String companyId) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                transferAccountsBatchService.buildAllInfo(type, companyId, tokenUser)
        );
    }

    @Override
    @GetMapping("/updateZfbAppAuthToken/{code}/{pid}")
    public Result<Integer> updateZfbAppAuthToken(@PathVariable String code, @PathVariable String pid) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                transferAccountsBatchService.updateZfbAppAuthToken(code, pid, tokenUser)
        );
    }


}

